package com.link.play.fit.ai.base

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.link.play.fit.ai.ext.launchContract
import com.link.play.fit.ai.utils.EventUtils

/**
 *
 * @param VB : ViewBinding
 * @property binding 绑定的视图数据
 * @constructor
 */
abstract class BaseActivity<VB : ViewBinding>(
    bindingInflater: (LayoutInflater) -> VB,
    private val logEvent: Boolean = true
) : AppCompatActivity() {

    open val TAG = javaClass.simpleName

    @Suppress("MemberVisibilityCanBePrivate")
    val binding by lazy(LazyThreadSafetyMode.NONE) {
        bindingInflater(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (logEvent) EventUtils.event("page_$TAG")
        enableEdgeToEdge()
        setContentView(binding.root)
        useDefaultImmersive()
    }

    open fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    fun setStatusBarColor(@ColorInt color: Int = Color.TRANSPARENT, isLight: Boolean = true) {
        enableEdgeToEdge(
            if (isLight) SystemBarStyle.light(color, color) else SystemBarStyle.dark(
                color
            )
        )
    }

//    fun finishToMainTop() {
//        val intent = Intent(this, MainAc::class.java)
//        intent.putExtra("where", "finishToMainTop")
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//        startActivity(intent)
//        finish()
//    }
}

inline fun <VB : ViewBinding> BaseActivity<VB>.viewBind(block: VB.() -> Unit) {
    binding.apply(block)
}

inline fun Activity.goToAc(
    clazz: Class<out Activity>,
    options: Bundle? = null,
    crossinline block: (Intent.() -> Unit) = {},
) {
    startActivity(Intent(this, clazz).apply(block), options)
}

suspend inline fun ComponentActivity.goToAcForResult(
    clazz: Class<out Activity>,
    options: ActivityOptionsCompat? = null,
    crossinline block: (Intent.() -> Unit) = {},
): ActivityResult {
    return launchContract(
        ActivityResultContracts.StartActivityForResult(),
        Intent(this@goToAcForResult, clazz).apply(block), options
    )
}